import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Icon, Row, Col } from 'antd';
import styles from './style.less';

import Header from './Header';
import drawCode from '@/components/Captcha';

class Login extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
    };
    this.captchaOption = { width: 85, height: 40, x: 20, y: 30 };
    this.captchaWrapper = React.createRef();
  }

  componentDidMount() {
    if (this.captchaWrapper.current) {
      this.setState({ captcha: drawCode(this.captchaWrapper.current, this.captchaOption) });
    }
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `login/clear` });
  }

  checkCaptcha(rule, value, callback) {
    if (!value || this.state.captcha.toLowerCase() !== value.toLowerCase()) {
      callback('请输入正确的验证码');
    } else {
      callback();
    }
  }

  handleSubmit = (e) => {
    const { dispatch, form } = this.props;

    e.preventDefault();
    form.validateFields(['username', 'password', 'captcha'], { force: true }, (err, values) => {
      if (!err) {
        dispatch({
          type: 'login/login',
          payload: {
            ...values,
            dispatch,
            onError: () => {
              form.setFieldsValue({ 'captcha': undefined })
              this.setState({ captcha: drawCode(this.captchaWrapper.current, this.captchaOption) });
            }
          },
        });
      }
    });
  };

  render() {
    const { form, loading, login } = this.props;
    const { getFieldDecorator } = form;
    const { loginError } = login;

    return (
      <div style={{ height: '100%' }}>
        <Row style={{ height: '100%', position: 'relative' }}>
          <Col xxl={{ span: 18 }} xl={{ span: 16 }} lg={{ span: 12 }} md={{ span: 12 }} sm={{ span: 12 }} xs={{ span: 12 }} style={{ backgroundImage: `url('/img/user-backgroud03.jpg')`, backgroundSize: '100% 100%', height: '100%' }}>

          </Col>
          <Col xxl={{ span: 6 }} xl={{ span: 8 }} lg={{ span: 12 }} md={{ span: 12 }} sm={{ span: 12 }} xs={{ span: 12 }} style={{ height: '100%', position: 'relative' }}>
            <div className={styles.main}>
              <Header loginError={loginError} />
              <div className={styles.login_form_wrapper}>
                <Form layout='vertical' hideRequiredMark onSubmit={this.handleSubmit}>
                  <Form.Item className={styles.affixWrapper}>
                    {getFieldDecorator('username', {
                      rules: [{ required: true, message: '请输入用户名' }]
                    })(
                      <Input
                        size='large'
                        placeholder='用户名'
                        prefix={<Icon type='user' />}
                      />
                    )}
                  </Form.Item>
                  <Form.Item className={styles.affixWrapper}>
                    {getFieldDecorator('password', {
                      initialValue: '',
                      rules: [{ required: true, message: '请输入密码' }]
                    })(
                      <Input.Password
                        size='large'
                        placeholder='密码'
                        prefix={<Icon type='lock' />}
                        type='password'
                      />
                    )}
                  </Form.Item>
                  <Form.Item className={[styles.affixWrapper, styles.captcha].join(' ')}>
                    {getFieldDecorator('captcha', {
                      validateTrigger: 'onBlur',
                      rules: [
                        { validator: (rule, value, callback) => this.checkCaptcha(rule, value, callback) }
                      ]
                    })(
                      <Input
                        size='large'
                        placeholder='验证码'
                        prefix={<Icon type='safety-certificate' />}
                        suffix={<div
                          ref={this.captchaWrapper}
                          style={{ width: 85, height: 40 }}
                          onClick={() => this.setState({ captcha: drawCode(this.captchaWrapper.current, this.captchaOption) })}
                        />}
                      />
                    )}
                  </Form.Item>
                  <Button className={styles.submit_button} htmlType='submit' size='large' type='primary' loading={loading.effects['login/login']}>
                    登录
              </Button>
                </Form>
              </div>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}

export default connect(({ login, loading }) => ({ login, loading }))(Form.create()(Login));
